<?php
namespace app\index\controller;
use app\index\logic\LoginLogic;

/**
 * 登录api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/05
 * Time: 16:13
 */
class Login extends Base {

    public function __construct(){
        parent::__construct();
        $this->l_logic = new LoginLogic();
    }

    /**
     * 登录
     * @return \think\response\Json
     */
    public function ajax_login(){
        $params = input();
        if(empty($params['code'])){
            return json($this->l_logic->get_response(0,'code不能为空'));
        }

        $appid = \think\facade\Config::get('xcx.xcx_appid');
        $appsecret = \think\facade\Config::get('xcx.xcx_appsecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $params['code'] . '&grant_type=authorization_code';
        $toosl = new \app\common\controller\Tools();
        $r = $toosl->GetuseCurl($url);
        $r = json_decode($r,true);
        if(isset($r['openid'])){
            session('openid',$r['openid']);
            $token = session_id();
            $data['token'] = $token;
            $data['openid'] = $r['openid'];
            $data['session_key'] = $r['session_key'];
            return json($this->l_logic->get_response(1,'OK',$data));
        }
        return json($this->l_logic->get_response(0,'请求失败，请重新进入'));
    }

    /**
     * 解密微信用户手机号
     * @return mixed
     */
    public function ajax_decrypt_wx_tel(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }
        $openid = session('openid');

        $appid = \think\facade\Config::get('xcx.xcx_appid');
        $sessionKey = $params['session_key'];
        $encryptedData = $params['encrypted_data'];
        $iv = $params['iv'];

        $pc = new \app\common\controller\WxBizDataCrypt($appid,$sessionKey);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);

        if($errCode == 0){
            $data = json_decode($data,true);
            $tel = isset($data['phoneNumber']) ? $data['phoneNumber'] : '';
            $r = $this->l_logic->save_user_tel($openid,$tel);

            return json($this->l_logic->get_response(1,'OK',$data));
        }
        return json($this->l_logic->get_response(0, '失败，errCode：' . $errCode));
    }
}
